package com.powernode.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     *
     * @param requestTemplate 即将要发起新的请求的请求对象
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtils.isNull(requestAttributes)) {
            // 获取当前请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            if (ObjectUtils.isNull(request)){
                // 将当前请求对象头里的token传递到下一个请求对象的请求头中
                requestTemplate.header(AuthConstants.AUTHORIZATION,request.getHeader(AuthConstants.AUTHORIZATION));
                return;
            }
        }
        requestTemplate.header(AuthConstants.AUTHORIZATION,requestAttributes.getRequest().getHeader(AuthConstants.AUTHORIZATION));
    }
     */
    /**
     *
     * @param requestTemplate 即将要发起新的请求的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取当前请求对象
        HttpServletRequest request = requestAttributes.getRequest();
        // 将当前请求对象头里的token传递到下一个请求对象的请求头中
        requestTemplate.header(AuthConstants.AUTHORIZATION,request.getHeader(AuthConstants.AUTHORIZATION));
    }
}